#include <iostream>
#include <memory>
#include <sstream>
#include "jsoncpp/json/json.h"
#include "jsoncpp/json/writer.h"
#include "jsoncpp/json/forwards.h"

bool serialize(const Json::Value &root, std::string &str)
{

    std::stringstream ss;
    // 先实例化一个工厂类
    Json::StreamWriterBuilder swb;

    // 再由工厂类对象来生产派生类对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(root, &ss);
    if (ret != 0)
    {
        std::cout << "json serialize failed" << std::endl;
        return false;
    }
    str = ss.str();
    std::cout << std::endl;
    return true;
}

bool unserialize(const std::string &str, Json::Value &root)
{
    // 实例化工厂对象
    Json::CharReaderBuilder crb;
    // 生产派生类对象
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    std::string errs;

    bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &root, &errs);
    if (ret == false)
    {
        std::cout << "josn unserialize failed : " << errs << std::endl;
        return false;
    }

    return true;
}

int main()
{
    const char *name = "kanade";
    int age = 18;
    const char *sex = "female";
    int score[3] = {100, 90, 80};

    Json::Value fav;
    fav[u8"音乐"] = "123";
    fav[u8"书籍"] = u8"宵崎朝比奈";

    Json::Value root;
    root["name"] = name;
    root["age"] = age;
    root["sex"] = sex;
    root["score"].append(score[0]);
    root["score"].append(score[1]);
    root["score"].append(score[2]);

    root[u8"爱好"] = fav;
    Json::Value root1;
    std::string body;
    bool ret = serialize(root1, body);

    std::string str = R"({"name":"kanade","age":18,"score":[100,90,80]})";

    Json::Value root2;
    bool ret1 = unserialize(str, root2);
    if (ret1 == false)
        return -1;

    std::cout << "name:" << root2["name"].asString() << std::endl;
    std::cout << "age:" << root2["age"].asInt() << std::endl;
    int sz = root2["score"].size();
    for (int i = 0; i < sz; i++)
    {
        std::cout << "score:" << root2["score"][i].asInt() << std::endl;
    }

    return 0;
}